<template>
  <div class="label-management">
    <a-space direction="vertical" style="width: 100%">
      <!-- 操作栏 -->
      <div class="action-bar">
        <a-button type="primary" @click="showModal">新增标签</a-button>
      </div>

      <!-- 标签表格 -->
      <a-table
        :columns="columns"
        :data-source="labelList"
        :loading="loading"
        row-key="labelId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'sortNum'">
            {{ record.sortNum || '-' }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除该标签吗？"
                @confirm="handleDelete(record.labelId)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 标签表单模态框 -->
      <a-modal
        v-model:visible="modalVisible"
        :title="modalTitle"
        @ok="handleSubmit"
        @cancel="resetForm"
      >
        <a-form :model="formState" layout="vertical" ref="formRef">
          <a-form-item
            label="标签名称"
            name="labelName"
            :rules="[{ required: true, message: '请输入标签名称!' }]"
          >
            <a-input v-model:value="formState.labelName" />
          </a-form-item>

          <a-form-item
            label="分类ID"
            name="categoryId"
            :rules="[{ required: true, message: '请选择分类!' }]"
          >
            <a-input-number
              v-model:value="formState.categoryId"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="排序顺序" name="sortNum">
            <a-input-number
              v-model:value="formState.sortNum"
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  addUsingPost1,
  deleteUsingPost1,
  queryAllUsingGet,
  updateUsingPost1
} from '@/api/equipmentLabelController'

interface Label {
  labelId?: number;
  labelName: string;
  categoryId: number;
  sortNum?: number;
}

const columns = [
  {
    title: '标签名称',
    dataIndex: 'labelName',
    key: 'labelName'
  },
  {
    title: '分类ID',
    dataIndex: 'categoryId',
    key: 'categoryId'
  },
  {
    title: '排序顺序',
    key: 'sortNum'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
]

const loading = ref(false)
const labelList = ref<API.EquipmentLabelDTO[]>([])
const modalVisible = ref(false)
const formRef = ref<FormInstance>()
const formState = ref<API.EquipmentLabelDTO>({
  labelName: '',
  categoryId: 0,
  sortNum: 0
})


const currentLabelId = ref<number | null>(null)

const modalTitle = computed(() =>
  currentLabelId.value !== null ? '编辑标签' : '新增标签'
)

// 显示新增模态框
const showModal = () => {
  currentLabelId.value = null  // 明确设置为null
  resetForm()
  modalVisible.value = true
}

// 加载标签列表
const loadLabels = async () => {
  try {
    loading.value = true
    const res = await queryAllUsingGet()
    if (res.data.code === 0) {
      labelList.value = res.data.data || []
    }
  } catch (error) {
    message.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 处理编辑
// 处理编辑（关键修改部分）
const handleEdit = (record: API.EquipmentLabelDTO) => {
  currentLabelId.value = record.id!  // 使用正确的ID字段
  formState.value = {
    ...record,
    categoryId: record.categoryId || 0, // 确保数值类型
    sortNum: record.sortNum || 0
  }
  modalVisible.value = true
}

// 处理删除
const handleDelete = async (id: number) => {
  try {
    const res = await deleteUsingPost1({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      loadLabels()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 提交表单（关键修改部分）
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    const payload: API.EquipmentLabelDTO = {
      ...formState.value,
      // 根据接口要求添加必要字段
      id: currentLabelId.value ?? undefined
    }

    if (currentLabelId.value !== null) {
      // 更新操作
      const res = await updateUsingPost1(payload)
      if (res.data.code === 0) {
        message.success('更新成功')
      }
    } else {
      // 新增操作
      const res = await addUsingPost1(payload)
      if (res.data.code === 0) {
        message.success('新增成功')
      }
    }

    modalVisible.value = false
    loadLabels()
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败，请检查数据')
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  formState.value = {
    labelName: '',
    categoryId: 0,
    sortNum: 0
  }
}

// 初始化加载数据
onMounted(() => {
  loadLabels()
})
</script>

<style scoped>
.label-management {
  padding: 24px;
  background: #fff;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.ant-space {
  width: 100%;
}
</style>
